//
//  ScanCodeViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/16.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "ScanCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ScanCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    NSTimer *_timer;
    UIImageView *_line;
    int num;
    BOOL upOrDown; //扫描条的上下状态。
}
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;


@end

@implementation ScanCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getImageToView];
    // Do any additional setup after loading the view.
  
}

- (void)getImageToView
{
    UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(15, 40, 290, 50)];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.numberOfLines=2;
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.text = @"将二维码图像置于矩形方框内，离手机摄像头10CM左右，系统会自动识别。";
    [self.view addSubview:labIntroudction];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(kScreenWidth / 2 - 30 , 500, 60, 30);
    [backButton addTarget:self action:@selector(leftButton) forControlEvents:UIControlEventTouchUpInside];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.view addSubview:backButton];
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 100, 300, 300)];
    imageView.image = [UIImage imageNamed:@"pick_bg@2x.png"];
    [self.view addSubview:imageView];
    
    upOrDown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(25, 110, 260, 2)];
    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(lineAnimation) userInfo:nil repeats:YES];

}

- (void)leftButton
{
    [self dismissViewControllerAnimated:YES completion:^{
        [_timer invalidate];
    }];
}

- (void)lineAnimation
{
    if (upOrDown == NO) {
        num ++;
        _line.frame = CGRectMake(25, 110+2*num, 260, 2);
        if (2*num == 260) {
            upOrDown = YES;
        }
    }else{
        num --;
        _line.frame = CGRectMake(25, 110+2*num, 260, 2);
        if (num == 0) {
            upOrDown = NO;
        }
    }
}

//试图将要消失
- (void)viewWillAppear:(BOOL)animated
{
    [self setupCamera];
}

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    NSError *error = nil;
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"警告" message:@"初始化输入设备失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [errorView show];
        return;
    }
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode128Code];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =CGRectMake(20,110,280,280);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //**

    NSString *stringValue;
    if ([metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    [_session stopRunning];

    [self dismissViewControllerAnimated:YES completion:^{
        [_timer invalidate];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringValue]];
    }];
}

#pragma mark - 内容警告触发方法
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
